package com.bytz.modules.system.controller;

import cn.hutool.core.io.IoUtil;
import com.bytz.common.api.vo.Result;
import com.bytz.common.constant.CommonConstant;
import com.bytz.common.exception.BytzBootException;
import com.bytz.common.system.api.ISysBaseApi;
import com.bytz.common.util.UploadUtil;
import com.bytz.common.util.oConvertUtils;
import com.bytz.modules.system.service.ICommonService;
import com.bytz.modules.system.vo.FilePreviewVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/common")
@Api(tags = "文件操作")
public class CommonController {

    @Autowired
    private ISysBaseApi sysBaseApi;

    @Value(value = "${bytz.path.upload}")
    private String uploadpath;

    /**
     * 本地：local minio：minio 阿里：alioss
     */
    @Value(value = "${bytz.uploadType}")
    private String uploadType;


    @Autowired
    private ICommonService commonService;

    @Autowired
    private UploadUtil uploadUtil;

    /**
     * 上传文件
     *
     * @param request
     * @param checkPlaceHolder
     * @param templateFileKey
     * @return
     */
    @PostMapping(value = "/upload")
    public Result<String> upload(HttpServletRequest request,
                            @RequestParam(value = "checkPlaceHolder", defaultValue = "0") String checkPlaceHolder,
                            @RequestParam(value = "templateFileKey", required = false) String templateFileKey,
                            @RequestParam(value = "quickSave", required = false, defaultValue = "false") boolean quickSave) throws Exception {
        Result<String> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("bizPath");

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象

        Result<String> validateResult = uploadUtil.uploadFileValidate(file, bizPath);
        if (!validateResult.isSuccess()) {
            return validateResult;
        }

        // 检查文档中的占位符
        commonService.checkPlaceHolders(file, bizPath, checkPlaceHolder, templateFileKey);

        if (oConvertUtils.isEmpty(bizPath)) {
            if (CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)) {
                result.setMessage("使用阿里云文件上传时，必须添加目录！");
                result.setSuccess(false);
                return result;
            } else {
                bizPath = "";
            }
        }

        if (quickSave) {
            savePath = commonService.quickUploadLocal(file, bizPath);
        } else {
            savePath = commonService.uploadLocal(file, bizPath);
        }

        result.setMessage(savePath);
        result.setResult(savePath);
        result.setSuccess(true);
        return result;
    }

    /**
     * 预览图片&下载文件
     * 请求地址：http://localhost:8080/common/static/12345678
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/static/{attachmentId}")
    public void view(@PathVariable("attachmentId") String attachmentId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        commonService.download(attachmentId, request, response);
    }


    /**
     * 可预览接口
     *
     * @param attachmentId
     */
    @ApiOperation("可预览接口")
    @GetMapping("/previewable/{attachmentId}")
    public Result<FilePreviewVo> previewable(@PathVariable("attachmentId") String attachmentId) {
        Result<FilePreviewVo> result = new Result<>();
        FilePreviewVo filePreviewVo = commonService.isPreviewable(attachmentId);
        result.setSuccess(true);
        result.setResult(filePreviewVo);
        return result;
    }

    /**
     * 预览接口
     *
     * @param attachmentId
     * @param response
     * @throws IOException
     */
    @ApiOperation("预览接口")
    @GetMapping("/preview/{attachmentId}")
    public void preview(@PathVariable("attachmentId") String attachmentId, HttpServletResponse response) throws Exception {
        commonService.preview(attachmentId, response);
    }

    /**
     * 将文件放入输出流内
     *
     * @param filePath
     * @param response
     * @throws IOException
     */
    private void returnFileStream(String filePath, HttpServletResponse response) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new BytzBootException("找不到文件: " + filePath);
        }

        try (BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
             try (OutputStream outputStream = response.getOutputStream()) {
                 IoUtil.copy(inputStream, outputStream);
            }
        }

        response.flushBuffer();
    }

    /**
     * 重试转换pdf接口
     *
     * @param attachmentId
     * @return
     */
    @ApiOperation("重试预览")
    @PostMapping("/retryPreview")
    public Result<FilePreviewVo> retryPreview(@RequestParam("attachmentId") String attachmentId) {
        Result<FilePreviewVo> result = new Result<>();
        FilePreviewVo filePreviewVo = commonService.retryPreview(attachmentId);
        result.setSuccess(true);
        result.setResult(filePreviewVo);
        return result;
    }

}
